package zrpc

import (
	"znet/glog"
	"znet/gorpc"
	"errors"
	"time"
)

type OnClientEvent interface {
	OnConnectionSuccess(client *RpcClient)
	OnConnectionFail(client *RpcClient)
}


type RpcClient struct {
	Addr string 			// 地址
	Name string 			// 服务id
	*gorpc.Dispatcher		// 派发器
	client *gorpc.Client	// 客户端
	*gorpc.DispatcherClient // 客户端派发器
	RequestTimeout int      // 请求超时时间 单位s
	OnClientEvent OnClientEvent	//
}
// 1.初始化化
func (this *RpcClient)Init() {
	this.Dispatcher = gorpc.NewDispatcher()
	if this.RequestTimeout <= 0 {
		// 默认rpc请求超时时间为5秒
		this.RequestTimeout = 5
	}
}
func (this *RpcClient)Start() error{
	if this.Addr == "" {
		glog.Error("Start RPC client Error: ","Addr is nil")
		return errors.New("addr is nil")
	}
	if this.Name == "" {
		glog.Error("Start RPC client Error: ","serverName is nil")
		return errors.New("serverName is nil")
	}
	if this.Dispatcher == nil {
		glog.Error("Start RPC client Error: ","Dispatcher is nil")
		return errors.New("dispatcher is nil")
	}
	this.client 				= gorpc.NewTCPClient(this.Addr)
	this.client.RequestTimeout 	= time.Duration(this.RequestTimeout) * time.Second
	this.client.OnClientEvent 	= this
	this.DispatcherClient 		= this.Dispatcher.NewServiceClient(this.Name,this.client)
	this.client.Start()
	glog.Info("Start RPC client Succeed: ",this.Addr)
	return nil
}
func (this *RpcClient)OnConnectionSuccess(){
	glog.Infof("[%s] (%s) 连接成功",this.Name,this.Addr)
	if this.OnClientEvent != nil {
		this.OnClientEvent.OnConnectionSuccess(this)
	}
}
func (this *RpcClient)OnConnectionFail(){
	glog.Errorf("[%s] (%s) 连接失败",this.Name,this.Addr)
	if this.OnClientEvent != nil {
		this.OnClientEvent.OnConnectionFail(this)
	}
}
func (this *RpcClient)Close(){
	if this.client != nil{
		this.client.Stop()
	}
}
func (this *RpcClient)IsConnected() bool{
	if this.client != nil{
		return this.client.IsConnected
	}
	return false
}